Skip to content

AstViewer

Base classes

Name Children Inherits
Splitter
prettyqt.widgets.splitter
Implements a splitter widget.

⋔ Inheritance diagram

graph TD
  764571958["custom_widgets.AstViewer"]
  3002750695["widgets.Splitter"]
  2122975160["widgets.SplitterMixin"]
  1689631995["widgets.FrameMixin"]
  829357528["widgets.WidgetMixin"]
  3227531497["core.ObjectMixin"]
  2751680898["builtins.object"]
  625385617["gui.PaintDeviceMixin"]
  2174143683["QtWidgets.QSplitter"]
  3822057598["QtWidgets.QFrame"]
  3620195106["QtWidgets.QWidget"]
  3984060476["QtCore.QObject"]
  37984305["Shiboken.Object"]
  673956333["QtGui.QPaintDevice"]
  3002750695 --> 764571958
  2122975160 --> 3002750695
  1689631995 --> 2122975160
  829357528 --> 1689631995
  3227531497 --> 829357528
  2751680898 --> 3227531497
  625385617 --> 829357528
  2751680898 --> 625385617
  2751680898 --> 829357528
  2751680898 --> 1689631995
  2751680898 --> 2122975160
  2174143683 --> 3002750695
  3822057598 --> 2174143683
  3620195106 --> 3822057598
  3984060476 --> 3620195106
  37984305 --> 3984060476
  2751680898 --> 37984305
  673956333 --> 3620195106
  37984305 --> 673956333

🛈 DocStrings

Bases: Splitter

Widget which displays an AST Tree next to the corresponding source code.

Selecting a node in the tree will highlight the corresponing text section in source.

widget = custom_widgets.AstViewer()
widget.show()
![Image title](../../images/astviewer.png)
AstViewer widget
Source code in prettyqt/custom_widgets/astviewer.py
class AstViewer(widgets.Splitter):
    """Widget which displays an AST Tree next to the corresponding source code.

    Selecting a node in the tree will highlight the corresponing text section in source.

    ``` py
    widget = custom_widgets.AstViewer()
    widget.show()
    ```

    <figure markdown>
      ![Image title](../../images/astviewer.png)
      <figcaption>AstViewer widget</figcaption>
    </figure>
    """

    def __init__(
        self,
        object_name="ast_viewer",
        **kwargs,
    ):
        super().__init__(orientation="horizontal", object_name=object_name, **kwargs)
        self.tree = widgets.TreeView()
        self.ast_textedit = widgets.PlainTextEdit()
        self.tabwidget = widgets.TabWidget()
        self.tabwidget.add_tab(self.tree, "Tree")
        self.tabwidget.add_tab(self.ast_textedit, "Dumped")

        self.textedit = custom_widgets.CodeEditor()
        self.textedit.set_syntaxhighlighter("python")
        self.textedit.textChanged.connect(self._on_text_change)
        self.add(self.tabwidget)
        self.add(self.textedit)

    def _on_text_change(self):
        self.set_ast(self.textedit.get_value())

    def _on_current_change(self, new_index: core.ModelIndex, _):
        node = new_index.data(constants.USER_ROLE)
        if not hasattr(node, "lineno"):
            return
        with self.textedit.selecter.current_cursor() as cursor:
            cursor.select_text(
                (node.lineno - 1, node.col_offset),
                (node.end_lineno - 1, node.end_col_offset),
            )

    def set_ast(self, ast_or_str: str | ast.AST):
        model = self.tree.get_model(skip_proxies=True)
        if not isinstance(model, itemmodels.AstModel):
            model = itemmodels.AstModel(ast_or_str, show_root=True, parent=self.tree)
            self.tree.set_model(model)
            self.tree.selectionModel().currentChanged.connect(self._on_current_change)
        else:
            model.set_ast(ast_or_str)
        self.tree.show_root(False)
        self.tree.expandAll()
        ast_tree = model.ast_tree
        text = ast_or_str if isinstance(ast_or_str, str) else ast.unparse(ast_or_str)
        with self.textedit.signals_blocked():
            self.textedit.set_text(text)
        dumped = ast.dump(ast_tree, indent=4) if ast_tree is not None else ""
        self.ast_textedit.set_text(dumped)

    def rename_variable(
        self,
        old: str,
        new: str,
        ignore: list[str] | None = None,
        scope: list[str] | None = None,
    ):
        """Rename all identifiers named `old` to `new` (see AstModel.rename_variable)."""
        model = self.tree.get_model(skip_proxies=True)
        if not isinstance(model, itemmodels.AstModel):
            raise TypeError(model)
        model.rename_variable(old, new, ignore=ignore, scope=scope)
        if model.ast_tree is not None:
            self.set_ast(model.ast_tree)

rename_variable(old: str, new: str, ignore: list[str] | None = None, scope: list[str] | None = None)

Rename all identifiers named old to new (see AstModel.rename_variable).

Source code in prettyqt/custom_widgets/astviewer.py
def rename_variable(
    self,
    old: str,
    new: str,
    ignore: list[str] | None = None,
    scope: list[str] | None = None,
):
    """Rename all identifiers named `old` to `new` (see AstModel.rename_variable)."""
    model = self.tree.get_model(skip_proxies=True)
    if not isinstance(model, itemmodels.AstModel):
        raise TypeError(model)
    model.rename_variable(old, new, ignore=ignore, scope=scope)
    if model.ast_tree is not None:
        self.set_ast(model.ast_tree)

:fa-brands-github: Show source on GitHub